package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-10-12
 * Time: 23:06
 */
public class UdpEchoServer {
    //创建一个socket对象，后续网卡操作的基础
    private DatagramSocket socket = null;

    public UdpEchoServer (int port) throws SocketException {
        //当创建DatagramSocket的时候，传入的port参数就表示手动指定端口号
        this.socket = new DatagramSocket(port);
    }

    public void run() throws IOException {
        System.out.println("服务端启动");
        while (true) {
            //requestPacket 数据报用来接收客户端传入的数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //使用receive方法来接受数据，并且将接收到的二进制数据输出到requestPacket中
            socket.receive(requestPacket);

            //将接收到的数据转换为字符串
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            //服务器端进行相应的业务处理
            String response = process(request);

            //responsePacket 用来接收服务器端做出业务之后的数据
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());

            //将服务器做出的响应数据传回客户端
            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s:%d] req = %s, res = %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.run();
    }
}
